package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;
import pl.edu.uj.tcs.blef.utils.Card;

public class ShowHandRequestHandler extends AbstractTableHandler {

	public ShowHandRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		if(table.getGame() == null) {
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			}catch(Exception e){}
		} else {
			Client requester = null;
			for(Client c: table.getPlayers()){
				if(c.getSocket().equals(socket)) requester = c;
			}
			
			if(requester == null){
				try {
					Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				}catch(Exception e){}
			} else {
				StringBuilder sb = new StringBuilder();
				sb.append("OK /show-hand" + '\n');
				sb.append("HAND-SIZE: " + table.getGame().getHands().get(requester).getHandSize());
				for(Card c: table.getGame().getHands().get(requester).getCards()){
					sb.append('\n');
					sb.append(c.getCode() + " " + c.getColor().getCode());
				}
				
				String[] param = new String[1];
				param[0] = sb.toString();
				try {
					Request r = new OKRequestFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
			}
		}
	}

}
